package com.example.myapplication;

import android.content.SharedPreferences;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.*;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "System.out.println";
    private String host = "tcp://120.77.86.191:1883";
    private String userName = "root";
    private String passWord = "root";
    private String mqtt_id = "smarthomeAndroid";
    private String mqtt_pub_topic = "/mysmarthome/sub";
    private String mqtt_sub_topic = "/mysmarthome/pub";
    private int led_flag =1;
    private ScheduledExecutorService scheduler;


    private MqttClient client;
    private MqttConnectOptions options;
    private Handler handler;

    private TextView Lx;
    private int auto_flat;
    private int led_flat;
    private int motor_flat;
    private int warn_flat;
    private int water_flat;

    private Button btn_auto;
    private Button btn_led;
    private Button btn_motor;
    private Button btn_warn;
    private Button btn_water;

    private TextView co2;
    private TextView temp;
    private TextView tuhum;
    private TextView rain;
    private TextView wet;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.temp = (TextView) findViewById(R.id.temp);
        this.wet = (TextView) findViewById(R.id.wet);
        this.Lx = (TextView) findViewById(R.id.Lx);
        this.co2 = (TextView) findViewById(R.id.co2);
        this.tuhum = (TextView) findViewById(R.id.tuhum);
        this.rain = (TextView) findViewById(R.id.rain);
        this.btn_warn = (Switch) findViewById(R.id.Btn_warn);
        this.btn_motor = (Switch) findViewById(R.id.Btn_motor);
        this.btn_led = (Switch) findViewById(R.id.Btn_led);
        this.btn_water = (Switch) findViewById(R.id.Btn_water);
        this.btn_auto = (Switch) findViewById(R.id.Btn_auto);
        this.btn_warn.setOnClickListener(new View.OnClickListener() {
            /* class com.example.smarthomeandroid.MainActivity.AnonymousClass2 */

            public void onClick(View v) {
                if (MainActivity.this.warn_flat == 0) {
                    MainActivity mainActivity = MainActivity.this;
                    mainActivity.publishmessageplus(mainActivity.mqtt_pub_topic, "{\"target\":\"BEEP\",\"value\":1}");
                    MainActivity.this.warn_flat = 1;
                    SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("itcast", 0);
                    sharedPreferences.getString("BEEP", "");
                    sharedPreferences.getInt("value", 1);
                    return;
                }
                MainActivity mainActivity2 = MainActivity.this;
                mainActivity2.publishmessageplus(mainActivity2.mqtt_pub_topic, "{\"target\":\"BEEP\",\"value\":0}");
                MainActivity.this.warn_flat = 0;
            }
        });
        this.btn_motor.setOnClickListener(new View.OnClickListener() {
            /* class com.example.smarthomeandroid.MainActivity.AnonymousClass3 */

            public void onClick(View v) {
                if (MainActivity.this.motor_flat == 0) {
                    MainActivity mainActivity = MainActivity.this;
                    mainActivity.publishmessageplus(mainActivity.mqtt_pub_topic, "{\"target\":\"Motor\",\"value\":1}");
                    MainActivity.this.motor_flat = 1;
                    return;
                }
                MainActivity mainActivity2 = MainActivity.this;
                mainActivity2.publishmessageplus(mainActivity2.mqtt_pub_topic, "{\"target\":\"Motor\",\"value\":0}");
                MainActivity.this.motor_flat = 0;
            }
        });
        this.btn_led.setOnClickListener(new View.OnClickListener() {
            /* class com.example.smarthomeandroid.MainActivity.AnonymousClass4 */

            public void onClick(View v) {
                if (MainActivity.this.led_flat == 0) {
                    MainActivity mainActivity = MainActivity.this;
                    mainActivity.publishmessageplus(mainActivity.mqtt_pub_topic, "{\"target\":\"LED\",\"value\":1}");
                    MainActivity.this.led_flat = 1;
                    return;
                }
                MainActivity mainActivity2 = MainActivity.this;
                mainActivity2.publishmessageplus(mainActivity2.mqtt_pub_topic, "{\"target\":\"LED\",\"value\":0}");
                MainActivity.this.led_flat = 0;
            }
        });
        this.btn_water.setOnClickListener(new View.OnClickListener() {
            /* class com.example.smarthomeandroid.MainActivity.AnonymousClass5 */

            public void onClick(View v) {
                if (MainActivity.this.water_flat == 0) {
                    MainActivity mainActivity = MainActivity.this;
                    mainActivity.publishmessageplus(mainActivity.mqtt_pub_topic, "{\"target\":\"Water\",\"value\":1}");
                    MainActivity.this.water_flat = 1;
                    return;
                }
                MainActivity mainActivity2 = MainActivity.this;
                mainActivity2.publishmessageplus(mainActivity2.mqtt_pub_topic, "{\"target\":\"Water\",\"value\":0}");
                MainActivity.this.water_flat = 0;
            }
        });
        this.btn_auto.setOnClickListener(new View.OnClickListener() {
            /* class com.example.smarthomeandroid.MainActivity.AnonymousClass6 */

            public void onClick(View v) {
                if (MainActivity.this.auto_flat == 0) {
                    MainActivity mainActivity = MainActivity.this;
                    mainActivity.publishmessageplus(mainActivity.mqtt_pub_topic, "{\"target\":\"SG\",\"value\":1}");
                    MainActivity.this.auto_flat = 1;
                    return;
                }
                MainActivity mainActivity2 = MainActivity.this;
                mainActivity2.publishmessageplus(mainActivity2.mqtt_pub_topic, "{\"target\":\"SG\",\"value\":0}");
                MainActivity.this.auto_flat = 0;
            }
        });

//**********************************************************//
        Mqtt_init();
        startReconnect();
        this.handler = new Handler() {
            /* class com.example.smarthomeandroid.MainActivity.AnonymousClass1 */

//            数据处理
//              数据格式  /mysmarthome/pub---{"Hum":60,"Temp":27,"Light":82.50,"T_Humi":731,"Led":0,"Beep":0,"Motor":0,"Water":0,"Rain":81,"Smoke":38,"abnormal":0}
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int i = msg.what;
                char c = 3;
                char c2 = 1;
                char c3 = 0;
                if (i == 3) {
                    String s = msg.obj.toString();

                    Log.i("all",s);

                    String[] a = s.split(",");  //以 “，”分割 s
                    for (i=0;i<a.length;i++){          //输出分割后数组
                        Log.i("imSplit",a[i]);
                    }


                    //湿度数据
                    // a[0]:  /mysmarthome/pub---{"Hum":60
                    int length_wet = a[0].length();
                    Log.i("length_wet", String.valueOf(length_wet));
                    String data_wet = a[0].substring(26);
                    Log.i("data_wet",data_wet);
                    TextView visible_wet = MainActivity.this.wet;
                    visible_wet.setText(data_wet);



                    //温度数据
                    // a[1]: "Temp":27
                    int length_temp = a[1].length();
                    Log.i("length_temp", String.valueOf(length_temp));
                    String data_temp = a[1].substring(7);
                    Log.i("data_temp",data_temp);
                    TextView visible_temp = MainActivity.this.temp;
                    visible_temp.setText(data_temp);

                    //光照数据
                    //a[2]: "Light":92.50
                    int length_light = a[2].length();
                    Log.i("length_light", String.valueOf(length_light));
                    String data_light = a[2].substring(8);
                    Log.i("data_light",data_light);
                    TextView visible_light = MainActivity.this.Lx;
                    visible_light.setText(data_light + "Lx");

                    //土壤湿度数据
                    //a[3]: "T_Humi":738
                    int length_tuhum = a[3].length();
                    Log.i("length_tuhum", String.valueOf(length_tuhum));
                    String data_tuhum = a[3].substring(9);
                    Log.i("data_tuhum",data_tuhum);
                    TextView visible_tuhum = MainActivity.this.tuhum;
                    visible_tuhum.setText(data_tuhum);

                    //雨水数据
                    //a[8]: "Rain":81
                    int length_rain = a[8].length();
                    Log.i("length_rain", String.valueOf(length_rain));
                    String data_rain = a[8].substring(7);
                    Log.i("data_rain",data_rain);
                    TextView visible_rain = MainActivity.this.rain;
                    visible_rain.setText(data_rain);

                    //雨水数据
                    //a[8]: "Rain":81
                    int length_co2 = a[9].length();
                    Log.i("length_rain", String.valueOf(length_co2));
                    String data_co2 = a[9].substring(8);
                    Log.i("data_co2",data_co2);
                    TextView visible_co2 = MainActivity.this.co2;
                    visible_co2.setText(data_co2);

                } else if (i == 30) {
                    Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_LONG).show();
                } else if (i == 31) {
                    Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_LONG).show();
                    try {
                        MainActivity.this.client.subscribe(MainActivity.this.mqtt_sub_topic, 1);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }
            }
        };




    }


    private void Mqtt_init()
    {
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(host, mqtt_id,
                    new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    System.out.println("connectionLost----------");
                    startReconnect();
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }
                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    System.out.println("messageArrived----------");
                    Message msg = new Message();
                    //封装message包
                    msg.what = 3;   //收到消息标志位
                    msg.obj = topicName + "---" + message.toString();
                    //发送messge到handler
                    handler.sendMessage(msg);    // hander 回传
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void Mqtt_connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if(!(client.isConnected()) )  //如果还未连接
                    {
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 31;
                        // 没有用到obj字段
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    // 没有用到obj字段
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }
    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    Mqtt_connect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }
    private void publishmessageplus(String topic,String message2)
    {
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setPayload(message2.getBytes());
        try {
            client.publish(topic,message);
        } catch (MqttException e) {

            e.printStackTrace();
        }
    }

}